package com.haitao.wavebbs.service;

import com.haitao.wavebbs.dao.UserRepository;
import com.haitao.wavebbs.entity.User;
import com.haitao.wavebbs.entity.UserBasicInformation;
import com.haitao.wavebbs.entity.tools.CredentialForNomally;
import com.haitao.wavebbs.tools.ControllerTools;
import com.haitao.wavebbs.tools.SecurityTools;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Objects;

/**
 * @author haitao
 * @data 2023/3/3
 */
@Service
public class UserService {

    public final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }


    /**   用户新账号注册
     *    前端字段检测：userAccount、password不能为空
     *    后端服务器插入字段: userHashPassword
     * @param user
     */
    public void userRegister(User user) throws Exception {
        Objects.requireNonNull(user.getUserAccount(),"用户账户不能为空");
        Objects.requireNonNull(user.getPassword(),"用户密码不能为空");
        if(userRepository.getUserByUserAccount(user.getUserAccount())!=null){
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"用户账号已被使用，请更换用户账号");
        }
        user.setUserHashPassword(ControllerTools.hashEncode(user.getPassword()));
        userRepository.save(user);
    }

    /**  用户登陆验证
     * 前端字段检测：userAccount、password不能为空
     * @return token
     */
    public String accessToken(CredentialForNomally credentialForNomally) throws Exception {
        Objects.requireNonNull(credentialForNomally.getUserAccount(),"用户账户不能为空");
        Objects.requireNonNull(credentialForNomally.getPassword(),"用户密码不能为空");
        User userByUserAccount = userRepository.getUserByUserAccount(credentialForNomally.getUserAccount());
        if (userByUserAccount==null){
            throw new Exception("用户账号不存在");
        }

        if (!ControllerTools.hashEncodeMatches(credentialForNomally.getPassword(),userByUserAccount.getUserHashPassword())){
            throw new Exception("用户密码错误");
        }
        //截此验证通过
        //创建token的用户数据对象
        HashMap<String, Object> claimsMap = new HashMap<>(3);
        claimsMap.put("userId",userByUserAccount.getUserId());
        claimsMap.put("NickName",userByUserAccount.getNickName());
        claimsMap.put("getUserAccount",userByUserAccount.getUserAccount());
        //生成token
        String token = SecurityTools.createJwt(claimsMap,SecurityTools.ttlMillis_defalut);
        return token;
    }

    /**
     * 解析token,生成User
     * @param token
     */
    public User resolveTokenToUser(String token) throws Exception {

        Claims claimsMap =null;
        try {
            claimsMap = SecurityTools.getClaimsFromJwt(token);
        }catch (Exception e){
            throw new Exception("token失效，请重新登陆",e);
        }
        User user = new User();
        user.setUserId((Integer) claimsMap.get("userId"));
        user.setNickName((String) claimsMap.get("NickName"));
        user.setNickName((String) claimsMap.get("getUserAccount"));
        return user;
    }

    /**
     * 根据用户Id获取用户基本信息
     * @param userId
     * @return
     * @throws Exception
     */
    public UserBasicInformation getUserBasicInformation(int userId) throws Exception {
        User userByUserAccount = userRepository.getUserByUserId(userId);
        Objects.requireNonNull(userByUserAccount,"该用户不存在");
        UserBasicInformation userBasicInformation = new UserBasicInformation();
        userBasicInformation.setUserId(userByUserAccount.getUserId());
        userBasicInformation.setUserAccount(userByUserAccount.getUserAccount());
        userBasicInformation.setNickName(userByUserAccount.getNickName());
        userBasicInformation.setCreateTime(userByUserAccount.getCreateTime());
        userBasicInformation.setAvatar(userByUserAccount.getAvatar());
        return userBasicInformation;
    }

}
